package com.ruoyi.teaching.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.li.work.domain.SysUserOnline;
import com.ruoyi.li.work.domain.vo.WorkDeptUserVO;
import com.ruoyi.li.work.mapper.PlatformUUserDeptMapper;
import com.ruoyi.li.work.mapper.SysDeptMapper;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.li.work.mapper.SysUserRoleMapper;
import com.ruoyi.teaching.domain.*;
import com.ruoyi.teaching.domain.vo.*;
import com.ruoyi.teaching.mapper.*;
import com.ruoyi.teaching.service.DataCentreService;
import com.ruoyi.teaching.utils.UniversalUtil;
import javafx.application.Platform;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DataCentreServiceImpl implements DataCentreService {
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private PlatformLLearnMapper learnMapper;
    @Autowired
    private PlatformEScoreMapper eScoreMapper;
    @Autowired
    private PlatformTScoreMapper tScoreMapper;
    @Autowired
    private PlatformNNotesMapper notesMapper;
    @Autowired
    private PlatformUUserDeptMapper userDeptMapper;
    @Autowired
    private PlatformCCourseMapper courseMapper;
    @Autowired
    private PlatformEExamMapper examMapper;
    @Autowired
    private PlatformTTaskMapper taskMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private PlatformUResourceMapper resourceMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private PlatformUVirtualMapper virtualMapper;
    @Autowired
    private PlatformFForumMapper forumMapper;
    @Autowired
    private PlatformSCollectMapper collectMapper;
    @Autowired
    private PlatformCCourseDeptMapper platformCCourseDeptMapper;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private PlatformCCourseOutlineMapper outlineMapper;
    @Autowired
    private PlatformUVirtualLearnTimeMapper virtualLearnTimeMapper;
    @Autowired
    private PlatformUVirtualStudyMapper virtualStudyMapper;
    @Autowired
    private PlatformCCourseLearnTimeMapper courseLearnTimeMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PlatformEEventMapper eventMapper;

    private static final String DOWNLOAD_COUNT_KEY = "resource_download_count";
    private static final String COURSE_VIEWS_KEY_PREFIX = "course:views:";
    private static final String VIRTUAL_VIEWS_KEY_PREFIX = "virtual:views:";
    private static final String VIRTUAL_SIMULATION_KEY = "learning:virtual";
    private static final String COURSE_KEY = "learning:course";
    private static final String lOOK_NUM = "looking:num";

    @Override
    public AjaxResult teacherData() {
        Long userId = SecurityUtils.getUserId();
        TeacherDataCenterVO teacherDataCenterVO = new TeacherDataCenterVO();

        /*
        上半部分数据
         */
        Map<String, Integer> TopMap = new HashMap<>();
        // 课程总数
        QueryWrapper<PlatformCCourse> platformCCourseQueryWrapper = new QueryWrapper<>();
        platformCCourseQueryWrapper.eq("create_id", userId);
        List<PlatformCCourse> platformCCourses = courseMapper.selectList(platformCCourseQueryWrapper);
        TopMap.put("courseNumber", platformCCourses.size());
        // 虚拟仿真总数
        QueryWrapper<PlatformUVirtual> platformUVirtualQueryWrapper = new QueryWrapper<>();
        platformUVirtualQueryWrapper.eq("create_id", userId);
        List<PlatformUVirtual> platformUVirtuals = virtualMapper.selectList(platformUVirtualQueryWrapper);
        TopMap.put("virtualNumber", platformUVirtuals.size());
        // 老师的学习课程
        QueryWrapper<PlatformLLearn> learnQueryWrapper = new QueryWrapper<>();
        learnQueryWrapper.eq("create_id", userId);
        learnQueryWrapper.eq("learn_type", 1);
        List<PlatformLLearn> platformLLearns = learnMapper.selectList(learnQueryWrapper);
        Set<Integer> learnCourseIds = new HashSet<>();
        if (CollectionUtils.isEmpty(platformLLearns)) {
            TopMap.put("learnCourseNumber", 0);
        } else {
            for (PlatformLLearn platformLLearn : platformLLearns) {
                learnCourseIds.add(platformLLearn.getProjectId());
            }
            TopMap.put("learnCourseNumber", learnCourseIds.size());
        }
        teacherDataCenterVO.setTop(TopMap);

        /*
        中间数据（课程分析）
         */
        // 课程学习人数
        List<Integer> courseIds = new ArrayList<>();
        for (PlatformCCourse platformCCourse : platformCCourses) {
            courseIds.add(platformCCourse.getId());
        }

        List<String> namesCourse = new ArrayList<>();
        List<String> valuesCourse = new ArrayList<>();

        if (!courseIds.isEmpty()) {
            // 查询学习人数
            QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
            platformLLearnQueryWrapper.in("project_id", courseIds);
            platformLLearnQueryWrapper.eq("learn_type", 1);
            List<PlatformLLearn> learnList = learnMapper.selectList(platformLLearnQueryWrapper);

            namesCourse.add("课程学习人数（人）");
            valuesCourse.add(learnList.size() + "");

            // 查询课程总时长
            QueryWrapper<PlatformCCourseOutline> outlineQueryWrapper = new QueryWrapper<>();
            outlineQueryWrapper.in("create_id", userId);
            outlineQueryWrapper.ne("parent_id", 0);
            outlineQueryWrapper.ne("video_duration", 0);
            List<PlatformCCourseOutline> outlineList = outlineMapper.selectList(outlineQueryWrapper);
            Integer allDuration = 0;
            for (PlatformCCourseOutline outline : outlineList) {
                allDuration += outline.getVideoDuration();
            }
            BigDecimal duration = new BigDecimal(allDuration).divide(new BigDecimal(60), 2, RoundingMode.HALF_UP);
            namesCourse.add("课程总时长（h）");
            valuesCourse.add(duration.toString());

            // 查询课程总浏览人数
            int allViewCount = 0;
            for (Integer courseId : courseIds) {
                String viewKey = COURSE_VIEWS_KEY_PREFIX + courseId;
                Object views = redisCache.getCacheMapValue(viewKey, "views");
                if (views != null) {
                    int viewCount = Integer.parseInt(views.toString());
                    allViewCount += viewCount;
                }
            }

            // 将浏览人数添加到结果中
            namesCourse.add("课程总浏览量（次）");
            valuesCourse.add(allViewCount + "");
        } else {
            // 如果 courseIds 为空，设置课程学习人数、课程总时长和浏览人数为0
            namesCourse.add("课程学习人数（人）");
            namesCourse.add("课程总时长(h)");
            namesCourse.add("课程总浏览量（次）");
            valuesCourse.add("0");
            valuesCourse.add("0");
            valuesCourse.add("0");

        }
        // 封装成 List<List<String>>
        List<List<String>> middleLeft = Arrays.asList(namesCourse, valuesCourse);
        // 最终设置 MiddleLeft 到 studentDataCenterVO
        teacherDataCenterVO.setMiddleLeft(middleLeft);
         /*
        中间数据（虚拟仿真实训分析）
         */
        List<String> namesVirtual = new ArrayList<>();
        List<String> valuesVirtual = new ArrayList<>();
        QueryWrapper<PlatformUVirtual> virtualQueryWrapper = new QueryWrapper<>();
        virtualQueryWrapper.eq("create_id", userId);
        List<PlatformUVirtual> virtualsOwn = virtualMapper.selectList(virtualQueryWrapper);
        if (CollectionUtils.isEmpty(virtualsOwn)) {
            namesVirtual.add("实训人次（次）");
            namesVirtual.add("实训人数（人）");
            namesVirtual.add("实训浏览量");
            valuesVirtual.add("0");
            valuesVirtual.add("0");
            valuesVirtual.add("0");
        } else {
            Set<Long> ownVirtualIds = new HashSet<>();
            virtualsOwn.forEach(v -> ownVirtualIds.add(v.getId()));
            QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
            platformLLearnQueryWrapper.eq("learn_type", 0);
            platformLLearnQueryWrapper.in("project_id", ownVirtualIds);
            List<PlatformLLearn> platformLLearnsVirtual = learnMapper.selectList(platformLLearnQueryWrapper);
            if (CollectionUtils.isEmpty(platformLLearnsVirtual)) {
                namesVirtual.add("实训人次（次）");
                namesVirtual.add("实训人数（人）");
                namesVirtual.add("实训浏览量");
                valuesVirtual.add("0");
                valuesVirtual.add("0");
                valuesVirtual.add("0");
            } else {
                namesVirtual.add("实训人次（次）");
                valuesVirtual.add(platformLLearnsVirtual.size() + "");
                Set<Integer> peopleIds = new HashSet<>();
                platformLLearnsVirtual.forEach(l -> peopleIds.add(l.getCreateId()));
                namesVirtual.add("实训人数（人）");
                valuesVirtual.add(peopleIds.size() + "");
                int allViewCount = 0;
                for (Long virtualId : ownVirtualIds) {
                    String viewKey = VIRTUAL_VIEWS_KEY_PREFIX + virtualId;
                    Object views = redisCache.getCacheMapValue(viewKey, "views");
                    if (views != null) {
                        int viewCount = Integer.parseInt(views.toString());
                        allViewCount += viewCount;
                    }
                }
                namesVirtual.add("实训浏览量");
                valuesVirtual.add(allViewCount + "");
            }
        }
        List<List<String>> middleRight = Arrays.asList(namesVirtual, valuesVirtual);
        teacherDataCenterVO.setMiddleRight(middleRight);

        // 课程笔记
        QueryWrapper<PlatformNNotes> platformNNotesQueryWrapper = new QueryWrapper<>();
        platformNNotesQueryWrapper.eq("create_id", userId);
        platformNNotesQueryWrapper.orderByDesc("id");
        List<PlatformNNotes> platformNNotes = notesMapper.selectList(platformNNotesQueryWrapper);
        teacherDataCenterVO.setBottom(platformNNotes);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", teacherDataCenterVO);
    }

    @Override
    public AjaxResult teacherCourse(Integer studyNumCourseId, Integer studentScoreCourseId, Integer workFinishCourseId) {
        // 存储最终返回数据的列表，包含学习人数、成绩分布和作业完成情况
        Map<String, List<EChartsInfoVO>> newInfo = new HashMap<>();

        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        // 构建课程查询条件，查询当前用户创建的已审核课程
        QueryWrapper<PlatformCCourse> courseQueryWrapper = new QueryWrapper<>();
        courseQueryWrapper.eq("create_id", userId); // 查询当前用户创建的课程
        // courseQueryWrapper.eq("vetting_status", 1); // 只查询审核通过的课程
        List<PlatformCCourse> courseList = courseMapper.selectList(courseQueryWrapper);

        // 如果用户没有创建课程
        if (CollectionUtils.isEmpty(courseList)) {
            // 设置学习人数统计为0
            List<EChartsInfoVO> courseNum = new ArrayList<>();
            EChartsInfoVO eChartsInfoVO = new EChartsInfoVO();
            eChartsInfoVO.setName("已学习");
            eChartsInfoVO.setValue(0);
            courseNum.add(eChartsInfoVO);
            EChartsInfoVO eChartsInfoVO1 = new EChartsInfoVO();
            eChartsInfoVO1.setName("未学习");
            eChartsInfoVO1.setValue(-1);
            courseNum.add(eChartsInfoVO1);
            newInfo.put("studyNum", courseNum);

            // 设置成绩分布为0
            List<EChartsInfoVO> StudentScore = getDefaultScoreInfo();
            newInfo.put("studentScore", StudentScore);

            // 设置作业完成情况为0
            List<EChartsInfoVO> workFinish = getDefaultWorkInfo();
            newInfo.put("workFinish", workFinish);

            // 返回空的数据，表示没有课程
            return new AjaxResult(HttpStatus.SUCCESS, "查询成功", newInfo);
        } else {
            // 存储当前用户创建的所有课程ID
            Set<Integer> ownCourseIds = new HashSet<>();
            courseList.forEach(c -> ownCourseIds.add(c.getId()));

            // 1. 查询课程的学习人数
            boolean haveNoStudy = false;
            QueryWrapper<PlatformLLearn> learnQueryWrapper = new QueryWrapper<>();
            learnQueryWrapper.eq("learn_type", 1); // 查询学习类型为课程学习的记录
            if (studyNumCourseId == null) {
                learnQueryWrapper.in("project_id", ownCourseIds); // 查询当前用户所有课程的学习记录
            } else {
                learnQueryWrapper.eq("project_id", studyNumCourseId); // 查询特定课程的学习记录
                PlatformCCourse platformCCourse = courseMapper.selectById(studyNumCourseId);
                haveNoStudy = (platformCCourse.getCourseVisible() == 1); // 判断课程是否是专业授课
            }

            // 获取学习记录列表
            List<PlatformLLearn> learnList = learnMapper.selectList(learnQueryWrapper);

            // 获取学习该课程的学生ID集合
            Set<Integer> peopleIds = new HashSet<>();
            learnList.forEach(l -> peopleIds.add(l.getCreateId()));

            // 计算已学习人数
            List<EChartsInfoVO> courseNum = new ArrayList<>();
            EChartsInfoVO eChartsInfoVO = new EChartsInfoVO();
            eChartsInfoVO.setName("已学习");
            eChartsInfoVO.setValue(peopleIds.size());
            courseNum.add(eChartsInfoVO);
            newInfo.put("studyNum", courseNum);

            // 如果课程未学习人数需要单独处理
            if (haveNoStudy) {
                handleNoStudyInfo(studyNumCourseId, peopleIds, courseNum);
                newInfo.put("studyNum", courseNum);
            } else {
                EChartsInfoVO eChartsInfoVO1 = new EChartsInfoVO();
                eChartsInfoVO1.setName("未学习");
                eChartsInfoVO1.setValue(-1);
                courseNum.add(eChartsInfoVO1);
            }

            // 2. 查询成绩分布
            List<EChartsInfoVO> StudentScore = getScoreDistribution(studentScoreCourseId, userId);
            newInfo.put("studentScore", StudentScore);

            // 3. 查询作业完成情况
            List<EChartsInfoVO> workFinish = getWorkFinishInfo(workFinishCourseId, userId);
            newInfo.put("workFinish", workFinish);

            // 返回数据
            return new AjaxResult(HttpStatus.SUCCESS, "查询成功", newInfo);
        }
    }

    @Override
    public AjaxResult teacherVirtual(Integer leftVirtualId, Integer rightVirtualId) {
        // 创建返回的视图对象
        TeacherDataVirtualVO teacherDataVirtualVO = new TeacherDataVirtualVO();
        List<EChartsHistogramVO> left = new ArrayList<>();  // 左侧数据
        List<EChartsInfoVO> right = new ArrayList<>();      // 右侧数据

        // 初始化ECharts图表的数据对象
        EChartsHistogramVO eChartsHistogramVO = new EChartsHistogramVO();

        // 获取当前用户的ID
        Long userId = SecurityUtils.getUserId();

        // 查找用户创建的所有虚拟仿真数据
        QueryWrapper<PlatformUVirtual> virtualQueryWrapper = new QueryWrapper<>();
        virtualQueryWrapper.eq("create_id", userId);
        List<PlatformUVirtual> platformUVirtuals = virtualMapper.selectList(virtualQueryWrapper);

        if (CollectionUtils.isEmpty(platformUVirtuals)) {
            // 如果没有找到虚拟仿真数据，初始化默认数据

            // 左侧数据：实训人数、实训人次、平均运行时长、最大浏览量
            String[] name = {"实训人数（人）", "实训人次（次）", "平均运行时长（min）", "最大浏览量"};
            String[] value = {"0", "0", "0", "0"};
            eChartsHistogramVO.setName(Arrays.asList(name));
            eChartsHistogramVO.setValue(Arrays.asList(value));
            left.add(eChartsHistogramVO);

            // 右侧数据：优秀率、合格率、不及格
            addDefaultRightData(right);

        } else {
            // 如果找到了虚拟仿真数据，进一步查询具体的数据

            HashSet<Long> virtualIds = new HashSet<>();
            for (PlatformUVirtual platformUVirtual : platformUVirtuals) {
                virtualIds.add(platformUVirtual.getId());
            }

            // 左侧数据：根据虚拟仿真ID查询学习记录
            addLeftData(leftVirtualId, virtualIds, left);

            // 右侧数据：根据虚拟仿真ID查询学习成绩
            addRightData(leftVirtualId, virtualIds, right);
        }

        // 将结果设置到返回的对象中
        teacherDataVirtualVO.setLeft(left);
        teacherDataVirtualVO.setRight(right);

        // 返回查询结果
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", teacherDataVirtualVO);
    }

    @Override
    public AjaxResult teacherStudy(Integer leftCourseId, Integer rightCourseId) {
        List<Map<String, String>> result = new ArrayList<>();
        Map<String, String> left = new HashMap<>();
        Map<String, String> right = new HashMap<>();
        Long userId = SecurityUtils.getUserId();

        QueryWrapper<PlatformLLearn> learnQueryWrapper = new QueryWrapper<>();
        learnQueryWrapper.eq("learn_type", 1);
        learnQueryWrapper.eq("learn_person_id", userId);
        List<PlatformLLearn> learnList = learnMapper.selectList(learnQueryWrapper);
        if (CollectionUtils.isEmpty(learnList)) {
            left.put("section", "0");
            right.put("duration", "0");
        } else {
            Set<Integer> courseIds = new HashSet<>();
            learnList.forEach(l -> courseIds.add(l.getProjectId()));

            /*
            左侧数据
             */
            int section = 0;
            if (null == leftCourseId) {
                for (Integer courseId : courseIds) {
                    Map<Long, Set<String>> courseLearningRecords = UniversalUtil.getCourseLearningRecords(Long.valueOf(courseId), redisCache);
                    if (courseLearningRecords != null && !courseLearningRecords.isEmpty()) {
                        section += courseLearningRecords.size();
                    }
                }
                left.put("section", String.valueOf(section));
            } else {
                Map<Long, Set<String>> courseLearningRecords = UniversalUtil.getCourseLearningRecords(Long.valueOf(leftCourseId), redisCache);
                if (courseLearningRecords != null && !courseLearningRecords.isEmpty()) {
                    section = courseLearningRecords.size();
                }
                left.put("section", String.valueOf(section));
            }


            /*
            右侧数据
             */
            QueryWrapper<PlatformCCourseLearnTime> courseLearnTimeQueryWrapper = new QueryWrapper<>();
            courseLearnTimeQueryWrapper.eq("user_id", userId);
            if (null == rightCourseId) {
                courseLearnTimeQueryWrapper.in("course_id", courseIds);
            } else {
                courseLearnTimeQueryWrapper.eq("course_id", rightCourseId);
            }
            List<PlatformCCourseLearnTime> courseLearnTimes = courseLearnTimeMapper.selectList(courseLearnTimeQueryWrapper);
            BigDecimal totalTime = calculateTotalLearnTimeC(courseLearnTimes, "h");
            right.put("duration", String.valueOf(totalTime));
        }

        result.add(left);
        result.add(right);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", result);
    }

    @Override
    public AjaxResult studentData() {
        Long userId = SecurityUtils.getUserId();
        StudentDataCenterVO studentDataCenterVO = new StudentDataCenterVO();

        /*
        顶部数据
         */
        QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
        platformLLearnQueryWrapper.eq("learn_person_id", userId);
        List<PlatformLLearn> platformLLearns = learnMapper.selectList(platformLLearnQueryWrapper);
        // 虚拟仿真
        List<PlatformLLearn> virtualSimulationList = platformLLearns.stream()
                .filter(item -> item.getLearnType() == 0)
                .collect(Collectors.toList());
        // 在线课程
        List<PlatformLLearn> onlineCourseList = platformLLearns.stream()
                .filter(item -> item.getLearnType() == 1)
                .collect(Collectors.toList());
        // 查询他题库练习过的虚拟仿真
        QueryWrapper<PlatformUVirtualStudy> virtualStudyQueryWrapper = new QueryWrapper<>();
        virtualStudyQueryWrapper.eq("create_id", userId);
        List<PlatformUVirtualStudy> platformUVirtualStudies = virtualStudyMapper.selectList(virtualStudyQueryWrapper);
        Set<Long> virtualIds = new HashSet<>();
        platformUVirtualStudies.forEach(puvs -> virtualIds.add(puvs.getVirtualId()));
        virtualSimulationList.forEach(vsl -> virtualIds.add(Long.valueOf(vsl.getProjectId())));

        Map<String, Integer> TopMap = new HashMap<>();
        TopMap.put("learnNumber", onlineCourseList.size());
        TopMap.put("virtualNumber", virtualIds.size());
        studentDataCenterVO.setTop(TopMap);

        /*
        中部数据（左侧）
         */
        EChartsInfoVO left = new EChartsInfoVO();
        if (CollectionUtils.isEmpty(onlineCourseList)) {
            left.setName(String.valueOf(0));
        } else {
            HashSet<Integer> courseIds = new HashSet<>();
            onlineCourseList.forEach(oc -> courseIds.add(oc.getProjectId()));
            QueryWrapper<PlatformCCourseLearnTime> courseLearnTimeQueryWrapper = new QueryWrapper<>();
            courseLearnTimeQueryWrapper.eq("user_id", userId);
            courseLearnTimeQueryWrapper.in("course_id", courseIds);
            List<PlatformCCourseLearnTime> courseLearnTimes = courseLearnTimeMapper.selectList(courseLearnTimeQueryWrapper);
            BigDecimal totalTime = calculateTotalLearnTimeC(courseLearnTimes, "h");
            left.setName(String.valueOf(totalTime));
        }
        studentDataCenterVO.setMiddleLeft(left);

        /*
        中部数据（右侧）
         */
        // 计算运行时长
        EChartsInfoVO right = new EChartsInfoVO();
        if (virtualIds.isEmpty()) {
            right.setName(String.valueOf(0));
        } else {
            QueryWrapper<PlatformUVirtualLearnTime> virtualLearnTimeQueryWrapper = new QueryWrapper<>();
            virtualLearnTimeQueryWrapper.in("pid", virtualIds);
            List<PlatformUVirtualLearnTime> virtualLearnTimeList = virtualLearnTimeMapper.selectList(virtualLearnTimeQueryWrapper);
            BigDecimal totalLearnTimeInMinutes = calculateTotalLearnTime(virtualLearnTimeList, "h");
            right.setName(String.valueOf(totalLearnTimeInMinutes));
        }
        studentDataCenterVO.setMiddleRight(right);

        /*
        底部数据
         */
        // 课程笔记
        QueryWrapper<PlatformNNotes> platformNNotesQueryWrapper = new QueryWrapper<>();
        platformNNotesQueryWrapper.eq("create_id", userId);
        platformNNotesQueryWrapper.orderByDesc("id");
        List<PlatformNNotes> platformNNotes = notesMapper.selectList(platformNNotesQueryWrapper);
        studentDataCenterVO.setBottom(platformNNotes);

        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", studentDataCenterVO);
    }

    @Override
    public AjaxResult studentStudy(Integer leftCourseId, Integer middleCourseId, Integer rightCourseId) {
        // 创建返回结果对象
        StudentDataCourseVO studentDataCourseVO = new StudentDataCourseVO();

        // 存储左侧数据（课时、学习时间）
        Map<String, String> left = new HashMap<>();

        // 存储中间数据（优秀率、合格率、不合格率）
        List<EChartsInfoVO> middle = new ArrayList<>();

        // 存储右侧数据（完成任务、未完成任务）
        List<EChartsInfoVO> right = new ArrayList<>();

        // 获取当前用户ID
        Long userId = SecurityUtils.getUserId();

        // 查询用户的学习记录
        QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
        platformLLearnQueryWrapper.eq("learn_person_id", userId);  // 用户ID
        platformLLearnQueryWrapper.eq("learn_type", 1);  // 学习类型，1表示正式学习
        List<PlatformLLearn> platformLLearns = learnMapper.selectList(platformLLearnQueryWrapper);

        // 如果没有学习记录，则填充默认值
        if (CollectionUtils.isEmpty(platformLLearns)) {
            // 左侧数据：默认没有课时和学习时间
            left.put("section", "0");
            left.put("studyTime", "0");

            // 中间数据：默认优秀率、合格率、不合格率为0
            addDefaultMiddleData(middle);

            // 右侧数据：默认完成任务、未完成任务为0
            addDefaultTaskData(right);
        } else {
            // 有学习记录时，提取课程ID
            Set<Integer> courseIds = new HashSet<>();
            platformLLearns.forEach(ll -> courseIds.add(ll.getProjectId()));

            // 处理左侧数据（课时和学习时间）
            processLeftData(left, leftCourseId, courseIds, userId);

            // 处理中间数据（优秀率、合格率、不合格率）
            processMiddleData(middle, middleCourseId, courseIds, userId);

            // 处理右侧数据（任务完成情况）
            processRightData(right, rightCourseId, courseIds, userId);
        }

        // 设置最终返回的VO对象
        studentDataCourseVO.setLeft(left);
        studentDataCourseVO.setMiddle(middle);
        studentDataCourseVO.setRight(right);

        // 返回查询成功的结果
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", studentDataCourseVO);
    }

    @Override
    public AjaxResult studentVirtualProject() {
        Long userId = SecurityUtils.getUserId();
        QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
        platformLLearnQueryWrapper.eq("learn_person_id", userId);
        platformLLearnQueryWrapper.eq("learn_type", 0);
        List<PlatformLLearn> platformLLearns = learnMapper.selectList(platformLLearnQueryWrapper);
        // 查询他题库练习过的虚拟仿真
        QueryWrapper<PlatformUVirtualStudy> virtualStudyQueryWrapper = new QueryWrapper<>();
        virtualStudyQueryWrapper.eq("create_id", userId);
        List<PlatformUVirtualStudy> platformUVirtualStudies = virtualStudyMapper.selectList(virtualStudyQueryWrapper);
        Set<Long> virtualIds = new HashSet<>();
        platformUVirtualStudies.forEach(puvs -> virtualIds.add(puvs.getVirtualId()));
        platformLLearns.forEach(vsl -> virtualIds.add(Long.valueOf(vsl.getProjectId())));
        QueryWrapper<PlatformUVirtual> virtualQueryWrapper = new QueryWrapper<>();
        if (virtualIds.isEmpty()) {
            List<PlatformUVirtual> virtuals = new ArrayList<>();
            return new AjaxResult(HttpStatus.SUCCESS, "查询成功", virtuals);
        } else {
            virtualQueryWrapper.in("id", virtualIds);
            List<PlatformUVirtual> virtuals = virtualMapper.selectList(virtualQueryWrapper);
            return new AjaxResult(HttpStatus.SUCCESS, "查询成功", virtuals);
        }
    }

    @Override
    public AjaxResult studentVirtual(Integer leftVirtualId, Integer rightVirtualId) {
        StudentDataVirtualVO studentDataVirtualVO = new StudentDataVirtualVO();
        Map<String, String> left = new HashMap<>();
        List<EChartsInfoVO> right = new ArrayList<>();
        Long userId = SecurityUtils.getUserId();

        /*
        左侧数据
         */
        QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
        platformLLearnQueryWrapper.eq("learn_person_id", userId);
        platformLLearnQueryWrapper.eq("learn_type", 0);
        List<PlatformLLearn> platformLLearns = learnMapper.selectList(platformLLearnQueryWrapper);
        // 查询他题库练习过的虚拟仿真
        QueryWrapper<PlatformUVirtualStudy> virtualStudyQueryWrapper = new QueryWrapper<>();
        virtualStudyQueryWrapper.eq("create_id", userId);
        List<PlatformUVirtualStudy> platformUVirtualStudies = virtualStudyMapper.selectList(virtualStudyQueryWrapper);
        Set<Long> virtualIds = new HashSet<>();
        platformUVirtualStudies.forEach(puvs -> virtualIds.add(puvs.getVirtualId()));
        platformLLearns.forEach(vsl -> virtualIds.add(Long.valueOf(vsl.getProjectId())));
        if (virtualIds.isEmpty()) {
            left.put("time", "0");
            left.put("number", "0");
            left.put("averageTime", "0");

            addDefaultMiddleData(right);
        } else {
            QueryWrapper<PlatformUVirtualLearnTime> virtualLearnTimeQueryWrapper = new QueryWrapper<>();
            virtualLearnTimeQueryWrapper.eq("uid", userId);
            if (leftVirtualId != null) {
                virtualLearnTimeQueryWrapper.eq("pid", leftVirtualId);
            } else {
                virtualLearnTimeQueryWrapper.in("pid", virtualIds);
            }
            List<PlatformUVirtualLearnTime> platformUVirtualLearnTimes = virtualLearnTimeMapper.selectList(virtualLearnTimeQueryWrapper);
            if (CollectionUtils.isEmpty(platformUVirtualLearnTimes)) {
                left.put("time", "0");
                left.put("number", "0");
                left.put("averageTime", "0");
            } else {
                BigDecimal allHour = calculateTotalLearnTime(platformUVirtualLearnTimes, "h");
                if (leftVirtualId != null) {
                    left.put("time", String.valueOf(allHour));
                    left.put("number", "0");
                    left.put("averageTime", "0");
                } else {
                    left.put("time", String.valueOf(allHour));
                    left.put("number", String.valueOf(platformUVirtualLearnTimes.size()));
                    left.put("averageTime", String.valueOf(allHour.divide(new BigDecimal(platformUVirtualLearnTimes.size()), 1, RoundingMode.HALF_UP)));
                }
            }
        }

        /*
        右侧数据
         */
        if (CollectionUtils.isEmpty(platformUVirtualStudies)) {
            addDefaultMiddleData(right);
        } else {
            int youXiu = 0;
            int heGe = 0;
            int buJiGe = 0;
            for (PlatformUVirtualStudy platformUVirtualStudy : platformUVirtualStudies) {
                Integer value = platformUVirtualStudy.getValue();
                if (value >= 85) {
                    youXiu++;
                } else if (value >= 60) {
                    heGe++;
                } else {
                    buJiGe++;
                }
            }
            EChartsInfoVO youXiuRateInfo = createEChartsInfoVO("优秀率", youXiu, "#2CB4FF");
            EChartsInfoVO heGeRateInfo = createEChartsInfoVO("合格率", heGe, "#51CE92");
            EChartsInfoVO buJiGeRateInfo = createEChartsInfoVO("不及格", buJiGe, "#ff9c39");
            right.add(youXiuRateInfo);
            right.add(heGeRateInfo);
            right.add(buJiGeRateInfo);
        }

        studentDataVirtualVO.setLeft(left);
        studentDataVirtualVO.setRight(right);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", studentDataVirtualVO);
    }

    @Override
    public AjaxResult commonEnterpriseData(Integer leftId, Integer rightId) {
        Long userId = SecurityUtils.getUserId();
        CommonEnterpriseDataVO commonEnterpriseDataVO = new CommonEnterpriseDataVO();

        /*
        顶部数据
         */
        QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
        platformLLearnQueryWrapper.eq("learn_person_id", userId);
        List<PlatformLLearn> platformLLearns = learnMapper.selectList(platformLLearnQueryWrapper);
        // 虚拟仿真
        List<PlatformLLearn> virtualSimulationList = platformLLearns.stream()
                .filter(item -> item.getLearnType() == 0)
                .collect(Collectors.toList());
        // 在线课程
        List<PlatformLLearn> onlineCourseList = platformLLearns.stream()
                .filter(item -> item.getLearnType() == 1)
                .collect(Collectors.toList());
        // 查询他题库练习过的虚拟仿真
        QueryWrapper<PlatformUVirtualStudy> virtualStudyQueryWrapper = new QueryWrapper<>();
        virtualStudyQueryWrapper.eq("create_id", userId);
        List<PlatformUVirtualStudy> platformUVirtualStudies = virtualStudyMapper.selectList(virtualStudyQueryWrapper);
        Set<Long> virtualIds = new HashSet<>();
        platformUVirtualStudies.forEach(puvs -> virtualIds.add(puvs.getVirtualId()));
        virtualSimulationList.forEach(vsl -> virtualIds.add(Long.valueOf(vsl.getProjectId())));

        Map<String, Integer> TopMap = new HashMap<>();
        TopMap.put("learnNumber", onlineCourseList.size());
        TopMap.put("virtualNumber", virtualIds.size());
        commonEnterpriseDataVO.setTop(TopMap);

        /*
        中间数据
         */
        // 存储左侧数据（课时、学习时间）
        Map<String, String> left = new HashMap<>();

        // 如果没有学习记录，则填充默认值
        if (CollectionUtils.isEmpty(platformLLearns)) {
            // 左侧数据：默认没有课时和学习时间
            left.put("section", "0");
            left.put("studyTime", "0");
        } else {
            // 有学习记录时，提取课程ID
            Set<Integer> courseIds = new HashSet<>();
            platformLLearns.forEach(ll -> courseIds.add(ll.getProjectId()));

            // 处理左侧数据（课时和学习时间）
            processLeftData(left, leftId, courseIds, userId);
        }
        commonEnterpriseDataVO.setMiddleLeft(left);
        // 右侧数据
        // 计算运行时长
        EChartsInfoVO right = new EChartsInfoVO();
        if (virtualIds.isEmpty()) {
            right.setName(String.valueOf(0));
        } else {
            QueryWrapper<PlatformUVirtualLearnTime> virtualLearnTimeQueryWrapper = new QueryWrapper<>();
            if (rightId == null) {
                virtualLearnTimeQueryWrapper.in("pid", virtualIds);
            } else {
                virtualLearnTimeQueryWrapper.eq("pid", rightId);
            }
            List<PlatformUVirtualLearnTime> virtualLearnTimeList = virtualLearnTimeMapper.selectList(virtualLearnTimeQueryWrapper);
            BigDecimal totalLearnTimeInMinutes = calculateTotalLearnTime(virtualLearnTimeList, "h");
            right.setName(String.valueOf(totalLearnTimeInMinutes));
        }
        commonEnterpriseDataVO.setMiddleRight(right);

        /*
        底部数据
         */
        // 课程笔记
        QueryWrapper<PlatformNNotes> platformNNotesQueryWrapper = new QueryWrapper<>();
        platformNNotesQueryWrapper.eq("create_id", userId);
        platformNNotesQueryWrapper.orderByDesc("id");
        List<PlatformNNotes> platformNNotes = notesMapper.selectList(platformNNotesQueryWrapper);
        commonEnterpriseDataVO.setBottom(platformNNotes);

        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", commonEnterpriseDataVO);
    }

    @Override
    public AjaxResult schoolManagerData(Integer topRightId, Integer middleLeftId) {
        // 获取当前用户 ID 和所属学校 ID
        Long userId = SecurityUtils.getUserId();
        Long schoolId = SecurityUtils.getLoginUser().getUser().getSchoolId();

        // 如果用户没有分配学校，返回错误信息
        if (null == schoolId) {
            return new AjaxResult(HttpStatus.ERROR, "暂无分配学校");
        }

        // 初始化数据对象
        SchoolManagerDataVO schoolManagerDataVO = new SchoolManagerDataVO();
        EChartsHistogramVO topLeft = new EChartsHistogramVO();
        EChartsHistogramVO topRight = new EChartsHistogramVO();
        List<EChartsInfoVO> middleLeft = new ArrayList<>();
        List<EChartsInfoVO> middleRight = new ArrayList<>();

        /*
         * 统计学校内院校、专业、班级数量（上部分左边）
         */
        List<String> name = new ArrayList<>();
        List<String> value = new ArrayList<>();

        SysDept sysDept = new SysDept();
        sysDept.setAncestors(schoolId.toString());
        sysDept.setStatus("0");
        List<SysDept> depts = deptMapper.selectDeptList(sysDept);

        if (CollectionUtils.isEmpty(depts)) {
            name.add("院校");
            value.add("0");
            name.add("专业");
            value.add("0");
            name.add("班级");
            value.add("0");
        } else {
            int universitiesNum = 0;
            int majorNum = 0;
            int classNum = 0;

            for (SysDept dept : depts) {
                if (dept.getDeptType() != null) {
                    if (dept.getDeptType() == 1) universitiesNum++;
                    else if (dept.getDeptType() == 2) majorNum++;
                    else if (dept.getDeptType() == 3) classNum++;
                }
            }

            name.add("院校");
            value.add(String.valueOf(universitiesNum));
            name.add("专业");
            value.add(String.valueOf(majorNum));
            name.add("班级");
            value.add(String.valueOf(classNum));
        }

        // 统计学校内教师和学生数量
        SysUser user = new SysUser();
        user.setSchoolId(schoolId);
        user.setRoleIds(2L); // 看sql理解
        user.setUserId(userId);
        List<SysUser> sysUsers = userMapper.selectUserList(user);

        if (CollectionUtils.isEmpty(sysUsers)) {
            name.add("教师");
            value.add("0");
            name.add("学生");
            value.add("0");
        } else {
            List<SysUser> teacherNum = new ArrayList<>();
            List<SysUser> studentNum = new ArrayList<>();

            for (SysUser sysUser : sysUsers) {
                Long[] roleId = userRoleMapper.selectRoleIdbyUserId(sysUser.getUserId());
                sysUser.setRoleIds(roleId[0]);

                if (sysUser.getRoleIds() == 3) {
                    teacherNum.add(sysUser);
                } else {
                    studentNum.add(sysUser);
                }
            }
            name.add("教师");
            value.add(String.valueOf(teacherNum.size()));
            name.add("学生");
            value.add(String.valueOf(studentNum.size()));
        }
        topLeft.setValue(value);
        topLeft.setName(name);

        /*
         * 统计指定时间段的院校、专业、班级数量（上部分右边）
         */
        LocalDate startDate = getStartDate(topRightId);
        ZoneId zoneId = ZoneId.systemDefault();
        List<String> nameRight = new ArrayList<>();
        List<String> valueRight = new ArrayList<>();

        if (CollectionUtils.isEmpty(depts)) {
            nameRight.add("院校");
            valueRight.add("0");
            nameRight.add("专业");
            valueRight.add("0");
            nameRight.add("班级");
            valueRight.add("0");
        } else {
            long universities = depts.stream()
                    .filter(d -> d.getCreateTime() != null && d.getDeptType() != null && d.getDeptType() == 1 &&
                            !d.getCreateTime().toInstant().atZone(zoneId).toLocalDate().isBefore(startDate))
                    .count();
            long major = depts.stream()
                    .filter(d -> d.getCreateTime() != null && d.getDeptType() != null && d.getDeptType() == 2 &&
                            !d.getCreateTime().toInstant().atZone(zoneId).toLocalDate().isBefore(startDate))
                    .count();
            long classInfo = depts.stream()
                    .filter(d -> d.getCreateTime() != null && d.getDeptType() != null && d.getDeptType() == 3 &&
                            !d.getCreateTime().toInstant().atZone(zoneId).toLocalDate().isBefore(startDate))
                    .count();

            nameRight.add("院校");
            valueRight.add(String.valueOf(universities));
            nameRight.add("专业");
            valueRight.add(String.valueOf(major));
            nameRight.add("班级");
            valueRight.add(String.valueOf(classInfo));
        }

        // 人员信息
        if (CollectionUtils.isEmpty(sysUsers)) {
            nameRight.add("教师");
            valueRight.add("0");
            nameRight.add("学生");
            valueRight.add("0");
        } else {
            // 筛选符合条件的用户数量（教师）
            long teacherCount = sysUsers.stream()
                    .filter(userInfo -> userInfo.getCreateTime() != null)
                    .filter(userInfo -> userInfo.getRoleIds() != null)
                    .filter(userInfo -> userInfo.getRoleIds() == 3)
                    .filter(userInfo -> {
                        LocalDate userCreateDate = userInfo.getCreateTime().toInstant().atZone(zoneId).toLocalDate();
                        return !userCreateDate.isBefore(startDate);  // 筛选用户创建时间在开始时间之后
                    })
                    .count();
            // 筛选符合条件的用户数量（学生）
            long studentCount = sysUsers.stream()
                    .filter(userInfo -> userInfo.getCreateTime() != null)
                    .filter(userInfo -> userInfo.getRoleIds() != null)
                    .filter(userInfo -> userInfo.getRoleIds() == 4)
                    .filter(userInfo -> {
                        LocalDate userCreateDate = userInfo.getCreateTime().toInstant().atZone(zoneId).toLocalDate();
                        return !userCreateDate.isBefore(startDate);  // 筛选用户创建时间在开始时间之后
                    })
                    .count();
            nameRight.add("教师");
            valueRight.add(String.valueOf(teacherCount));
            nameRight.add("学生");
            valueRight.add(String.valueOf(studentCount));
        }

        topRight.setName(nameRight);
        topRight.setValue(valueRight);

        /*
         * 统计课程审核情况（中间左边）
         */
        QueryWrapper<PlatformCCourse> courseQuery = new QueryWrapper<>();
        List<Long> userIds = sysUserMapper.selectUserListBySchoolId(schoolId).stream().map(SysUser::getUserId).collect(Collectors.toList());
        if (!userIds.isEmpty()) {
            courseQuery.in("create_id", userIds);
        }
        List<PlatformCCourse> courses = courseMapper.selectList(courseQuery);
        long unaudited = courses.stream().filter(c -> c.getVettingStatus() == 0).count();
        middleLeft.add(createEChartsInfoVO("未审核课程", (int) unaudited, "#CE5151"));
        middleLeft.add(createEChartsInfoVO("已审核课程", courses.size() - (int) unaudited, "#51CE92"));

        /*
         * 统计赛事情况（中间右边）
         */
        QueryWrapper<PlatformEEvent> eventQuery = new QueryWrapper<>();
        eventQuery.in("create_id", userIds);
        List<PlatformEEvent> events = eventMapper.selectList(eventQuery);
        long schoolLevel = events.stream().filter(e -> e.getEventLevel() == 0).count();
        long provinceLevel = events.stream().filter(e -> e.getEventLevel() == 1).count();
        long nationalLevel = events.stream().filter(e -> e.getEventLevel() == 2).count();
        middleRight.add(createEChartsInfoVO("校级赛事", (int) schoolLevel, "#2CB4FF"));
        middleRight.add(createEChartsInfoVO("省级赛事", (int) provinceLevel, "#FF9C39"));
        middleRight.add(createEChartsInfoVO("国家级赛事", (int) nationalLevel, "#CE5151"));

        schoolManagerDataVO.setTopLeft(topLeft);
        schoolManagerDataVO.setTopRight(topRight);
        schoolManagerDataVO.setMiddleLeft(middleLeft);
        schoolManagerDataVO.setMiddleRight(middleRight);

        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", schoolManagerDataVO);
    }

    @Override
    public AjaxResult systemManagerData(Integer topRightId, Integer middleMiddleId) {
        AdminManagerDataVO adminManagerDataVO = new AdminManagerDataVO();
        EChartsHistogramVO topLeft = new EChartsHistogramVO();
        EChartsHistogramVO topRight = new EChartsHistogramVO();
        List<EChartsInfoVO> middleLeft = new ArrayList<>();
        String middleMiddle = "";
        EChartsHistogramVO middleRightLeft = new EChartsHistogramVO();
        String middleRightRight = "";
        EChartsHistogramVO bottom = new EChartsHistogramVO();
        Long userId = SecurityUtils.getUserId();

        /*
        左上角数据
         */
        List<String> name = new ArrayList<>();
        List<String> value = new ArrayList<>();

        SysDept sysDept = new SysDept();
        sysDept.setStatus("0");
        sysDept.setDeptType(0);
        List<SysDept> depts = deptMapper.selectDeptList(sysDept);

        if (CollectionUtils.isEmpty(depts)) {
            name.add("院校");
            value.add("0");
        } else {
            name.add("院校");
            value.add(String.valueOf(depts.size()));
        }
        // 统计人员数量
        SysUser user = new SysUser();
        Long[] longs = userRoleMapper.selectRoleIdbyUserId(userId);
        user.setRoleIds(longs[0]); // 看sql理解
        user.setUserId(userId);
        List<SysUser> sysUsers = userMapper.selectUserList(user);

        if (CollectionUtils.isEmpty(sysUsers)) {
            name.add("普通用户");
            value.add("0");
            name.add("学生用户");
            value.add("0");
            name.add("教师用户");
            value.add("0");
            name.add("企业用户");
            value.add("0");
            name.add("管理员用户");
            value.add("0");
        } else {
            List<SysUser> teacherNum = new ArrayList<>();
            List<SysUser> studentNum = new ArrayList<>();
            List<SysUser> commonNum = new ArrayList<>();
            List<SysUser> enterpriseNum = new ArrayList<>();
            List<SysUser> adminNum = new ArrayList<>();

            for (SysUser sysUser : sysUsers) {
                Long[] roleId = userRoleMapper.selectRoleIdbyUserId(sysUser.getUserId());
                sysUser.setRoleIds(roleId[0]);

                if (sysUser.getRoleIds() == 3) {
                    teacherNum.add(sysUser);
                } else if (sysUser.getRoleIds() == 4) {
                    studentNum.add(sysUser);
                } else if (sysUser.getRoleIds() == 5) {
                    commonNum.add(sysUser);
                } else if (sysUser.getRoleIds() == 6) {
                    adminNum.add(sysUser);
                } else if (sysUser.getRoleIds() == 7) {
                    enterpriseNum.add(sysUser);
                }
            }
            name.add("普通用户");
            value.add(String.valueOf(commonNum.size()));
            name.add("学生用户");
            value.add(String.valueOf(studentNum.size()));
            name.add("教师用户");
            value.add(String.valueOf(teacherNum.size()));
            name.add("企业用户");
            value.add(String.valueOf(enterpriseNum.size()));
            name.add("管理员用户");
            value.add(String.valueOf(adminNum.size()));
        }
        topLeft.setValue(value);
        topLeft.setName(name);

        /*
        右上角数据
         */
        LocalDate startDate = getStartDate(topRightId);
        ZoneId zoneId = ZoneId.systemDefault();
        List<String> nameRight = new ArrayList<>();
        List<String> valueRight = new ArrayList<>();

        if (CollectionUtils.isEmpty(depts)) {
            nameRight.add("院校");
            valueRight.add("0");
        } else {
            long universities = depts.stream()
                    .filter(d -> d.getCreateTime() != null)
                    .filter(d -> d.getDeptType() != null)
                    .filter(d -> d.getDeptType() == 0)
                    .filter(d -> !d.getCreateTime().toInstant().atZone(zoneId).toLocalDate().isBefore(startDate))
                    .count();

            nameRight.add("院校");
            valueRight.add(String.valueOf(universities));
        }

        // 人员信息
        if (CollectionUtils.isEmpty(sysUsers)) {
            nameRight.add("普通用户");
            valueRight.add("0");
            nameRight.add("学生用户");
            valueRight.add("0");
            nameRight.add("教师用户");
            valueRight.add("0");
            nameRight.add("企业用户");
            valueRight.add("0");
            nameRight.add("管理员用户");
            valueRight.add("0");
        } else {
            // 筛选符合条件的用户数量（教师）
            long teacherCount = sysUsers.stream()
                    .filter(userInfo -> userInfo.getCreateTime() != null)
                    .filter(userInfo -> userInfo.getRoleIds() != null)
                    .filter(userInfo -> userInfo.getRoleIds() == 3)
                    .filter(userInfo -> {
                        LocalDate userCreateDate = userInfo.getCreateTime().toInstant().atZone(zoneId).toLocalDate();
                        return !userCreateDate.isBefore(startDate);  // 筛选用户创建时间在开始时间之后
                    })
                    .count();
            // 筛选符合条件的用户数量（学生）
            long studentCount = sysUsers.stream()
                    .filter(userInfo -> userInfo.getCreateTime() != null)
                    .filter(userInfo -> userInfo.getRoleIds() != null)
                    .filter(userInfo -> userInfo.getRoleIds() == 4)
                    .filter(userInfo -> {
                        LocalDate userCreateDate = userInfo.getCreateTime().toInstant().atZone(zoneId).toLocalDate();
                        return !userCreateDate.isBefore(startDate);  // 筛选用户创建时间在开始时间之后
                    })
                    .count();
            // 筛选符合条件的用户数量（普通用户）
            long commonCount = sysUsers.stream()
                    .filter(userInfo -> userInfo.getCreateTime() != null)
                    .filter(userInfo -> userInfo.getRoleIds() != null)
                    .filter(userInfo -> userInfo.getRoleIds() == 5)
                    .filter(userInfo -> {
                        LocalDate userCreateDate = userInfo.getCreateTime().toInstant().atZone(zoneId).toLocalDate();
                        return !userCreateDate.isBefore(startDate);  // 筛选用户创建时间在开始时间之后
                    })
                    .count();
            // 筛选符合条件的用户数量（企业用户）
            long enterpriseCount = sysUsers.stream()
                    .filter(userInfo -> userInfo.getCreateTime() != null)
                    .filter(userInfo -> userInfo.getRoleIds() != null)
                    .filter(userInfo -> userInfo.getRoleIds() == 7)
                    .filter(userInfo -> {
                        LocalDate userCreateDate = userInfo.getCreateTime().toInstant().atZone(zoneId).toLocalDate();
                        return !userCreateDate.isBefore(startDate);  // 筛选用户创建时间在开始时间之后
                    })
                    .count();
            // 筛选符合条件的用户数量（管理员用户）
            long adminCount = sysUsers.stream()
                    .filter(userInfo -> userInfo.getCreateTime() != null)
                    .filter(userInfo -> userInfo.getRoleIds() != null)
                    .filter(userInfo -> userInfo.getRoleIds() == 6)
                    .filter(userInfo -> {
                        LocalDate userCreateDate = userInfo.getCreateTime().toInstant().atZone(zoneId).toLocalDate();
                        return !userCreateDate.isBefore(startDate);  // 筛选用户创建时间在开始时间之后
                    })
                    .count();

            nameRight.add("普通用户");
            valueRight.add(String.valueOf(commonCount));
            nameRight.add("学生用户");
            valueRight.add(String.valueOf(studentCount));
            nameRight.add("教师用户");
            valueRight.add(String.valueOf(teacherCount));
            nameRight.add("企业用户");
            valueRight.add(String.valueOf(enterpriseCount));
            nameRight.add("管理员用户");
            valueRight.add(String.valueOf(adminCount));
        }
        topRight.setName(nameRight);
        topRight.setValue(valueRight);

        /*
        中间最左边（在线用户）
         */
        Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        if(CollectionUtils.isEmpty(keys)){
            middleLeft.add(createEChartsInfoVO("学生用户", 0, "#2CB4FF"));
            middleLeft.add(createEChartsInfoVO("教师用户", 0, "#51CE92"));
            middleLeft.add(createEChartsInfoVO("企业用户", 0, "#FF9C39"));
            middleLeft.add(createEChartsInfoVO("普通用户", 0, "#FF6139"));
            middleLeft.add(createEChartsInfoVO("管理员", 0, "#FF3939"));
        }else {
            List<SysUser> teacherNum = new ArrayList<>();
            List<SysUser> studentNum = new ArrayList<>();
            List<SysUser> commonNum = new ArrayList<>();
            List<SysUser> enterpriseNum = new ArrayList<>();
            List<SysUser> adminNum = new ArrayList<>();
            Set<Long> userIds = new HashSet<>();
            for (String key : keys) {
                LoginUser loginUser = redisCache.getCacheObject(key);
                SysUser sysUser = loginUser.getUser();
                userIds.add(sysUser.getUserId());
            }
            for (Long id : userIds) {
                SysUser sysUser = userMapper.selectUserById(id);
                Long[] roleId = userRoleMapper.selectRoleIdbyUserId(sysUser.getUserId());
                sysUser.setRoleIds(roleId[0]);

                if (sysUser.getRoleIds() == 3) {
                    teacherNum.add(sysUser);
                } else if (sysUser.getRoleIds() == 4) {
                    studentNum.add(sysUser);
                } else if (sysUser.getRoleIds() == 5) {
                    commonNum.add(sysUser);
                } else if (sysUser.getRoleIds() == 6) {
                    adminNum.add(sysUser);
                } else if (sysUser.getRoleIds() == 7) {
                    enterpriseNum.add(sysUser);
                }
            }
            middleLeft.add(createEChartsInfoVO("学生用户", studentNum.size(), "#2CB4FF"));
            middleLeft.add(createEChartsInfoVO("教师用户", teacherNum.size(), "#51CE92"));
            middleLeft.add(createEChartsInfoVO("企业用户", enterpriseNum.size(), "#FF9C39"));
            middleLeft.add(createEChartsInfoVO("普通用户", commonNum.size(), "#FF6139"));
            middleLeft.add(createEChartsInfoVO("管理员", adminNum.size(), "#FF3939"));
        }

        /*
        中间的中间部分
         */
        if(CollectionUtils.isEmpty(sysUsers)){
            middleMiddle = "0";
        }else {
            Set<Long> userIds = new HashSet<>();
            if(middleMiddleId == null || middleMiddleId == 0){
                List<SysUser> sysUserList = sysUsers.stream().filter(s -> s.getRoleIds() != null)
                        .filter(s -> s.getRoleIds() != 1)
                        .filter(s -> s.getRoleIds() != 2)
                        .collect(Collectors.toList());
                if(CollectionUtils.isEmpty(sysUserList)){
                    middleMiddle = "0";
                }else {
                    sysUserList.forEach(s -> userIds.add(s.getUserId()));
                    QueryWrapper<PlatformUVirtualLearnTime> virtualLearnTimeQueryWrapper = new QueryWrapper<>();
                    virtualLearnTimeQueryWrapper.in("uid", userIds);
                    List<PlatformUVirtualLearnTime> virtualLearnTimes = virtualLearnTimeMapper.selectList(virtualLearnTimeQueryWrapper);
                    BigDecimal totalLearnTimeInMinutes = calculateTotalLearnTime(virtualLearnTimes, "h");
                    middleMiddle = totalLearnTimeInMinutes.toString();
                }
            }else {
                List<SysUser> sysUserList = sysUsers.stream().filter(s -> s.getRoleIds() != null)
                        .filter(s -> s.getRoleIds() == middleMiddleId.longValue())
                        .collect(Collectors.toList());
                if(CollectionUtils.isEmpty(sysUserList)){
                    middleMiddle = "0";
                }else {
                    sysUserList.forEach(s -> userIds.add(s.getUserId()));
                    QueryWrapper<PlatformUVirtualLearnTime> virtualLearnTimeQueryWrapper = new QueryWrapper<>();
                    virtualLearnTimeQueryWrapper.in("uid", userIds);
                    List<PlatformUVirtualLearnTime> virtualLearnTimes = virtualLearnTimeMapper.selectList(virtualLearnTimeQueryWrapper);
                    BigDecimal totalLearnTimeInMinutes = calculateTotalLearnTime(virtualLearnTimes, "h");
                    middleMiddle = totalLearnTimeInMinutes.toString();
                }
            }
        }

        /*
        中间右边那块的左边
         */
        List<String> nameRightLeft = new ArrayList<>();
        List<String> valueRightLeft = new ArrayList<>();
        int virtualOnline = getOnlineLearningCount(0);
        nameRightLeft.add("运行仿真实训");
        valueRightLeft.add(String.valueOf(virtualOnline));
        int courseOnline = getOnlineLearningCount(1);
        nameRightLeft.add("运行在线课程");
        valueRightLeft.add(String.valueOf(courseOnline));
        middleRightLeft.setName(nameRightLeft);
        middleRightLeft.setValue(valueRightLeft);

        /*
        中间右边那块的右边
         */
        Object cacheValue = redisCache.getCacheObject(lOOK_NUM);
        middleRightRight = cacheValue == null ? "0" : (cacheValue instanceof String ? (String) cacheValue : String.valueOf(cacheValue));


        /*
        底部数据
         */
        List<String> nameBottom = new ArrayList<>();
        List<String> valueBottom = new ArrayList<>();
        QueryWrapper<PlatformUResource> resourceQueryWrapper = new QueryWrapper<>();
        resourceQueryWrapper.eq("vetting_status", 1);
        List<PlatformUResource> platformUResources = resourceMapper.selectList(resourceQueryWrapper);
        if(CollectionUtils.isEmpty(platformUResources)){
            nameBottom.add("图片数量");
            valueBottom.add("0");
            nameBottom.add("文档数量");
            valueBottom.add("0");
            nameBottom.add("课件数量");
            valueBottom.add("0");
            nameBottom.add("视频数量");
            valueBottom.add("0");
            nameBottom.add("模型素材");
            valueBottom.add("0");
        }else {
            long imageCount = platformUResources.stream().filter(r -> r.getResourceType() == 1).count();
            long documentCount = platformUResources.stream().filter(r -> r.getResourceType() == 0).count();
            long coursewareCount = platformUResources.stream().filter(r -> r.getResourceType() == 3).count();
            long videoCount = platformUResources.stream().filter(r -> r.getResourceType() == 2).count();
            long modelCount = platformUResources.stream().filter(r -> r.getResourceType() == 4).count();

            nameBottom.add("图片数量");
            valueBottom.add(String.valueOf(imageCount));
            nameBottom.add("文档数量");
            valueBottom.add(String.valueOf(documentCount));
            nameBottom.add("课件数量");
            valueBottom.add(String.valueOf(coursewareCount));
            nameBottom.add("视频数量");
            valueBottom.add(String.valueOf(videoCount));
            nameBottom.add("模型素材");
            valueBottom.add(String.valueOf(modelCount));
        }
        QueryWrapper<PlatformUVirtual> virtualQueryWrapper = new QueryWrapper<>();
        virtualQueryWrapper.eq("vetting_status", 1);
        List<PlatformUVirtual> platformUVirtals = virtualMapper.selectList(virtualQueryWrapper);
        if(CollectionUtils.isEmpty(platformUVirtals)){
            nameBottom.add("仿真软件");
            valueBottom.add("0");
        }else {
            long virtualCount = platformUVirtals.size();
            nameBottom.add("仿真软件");
            valueBottom.add(String.valueOf(virtualCount));
        }
        bottom.setValue(valueBottom);
        bottom.setName(nameBottom);

        adminManagerDataVO.setBottom(bottom);
        adminManagerDataVO.setTopLeft(topLeft);
        adminManagerDataVO.setTopRight(topRight);
        adminManagerDataVO.setMiddleLeft(middleLeft);
        adminManagerDataVO.setMiddleMiddle(middleMiddle);
        adminManagerDataVO.setMiddleRightLeft(middleRightLeft);
        adminManagerDataVO.setMiddleRightRight(middleRightRight);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", adminManagerDataVO);
    }

    @Override
    public void addVisit() {
        redisCache.increment(lOOK_NUM,1);
    }


    // 添加默认的中间数据（优秀率、合格率、不合格率）
    private void addDefaultMiddleData(List<EChartsInfoVO> middle) {
        middle.add(createEChartsInfoVO("优秀率", 0, "#2CB4FF"));
        middle.add(createEChartsInfoVO("合格率", 0, "#51CE92"));
        middle.add(createEChartsInfoVO("不及格", 0, "#ff9c39"));
    }

    // 添加默认的右侧数据（完成任务、未完成任务）
    private void addDefaultTaskData(List<EChartsInfoVO> right) {
        right.add(createEChartsInfoVO("完成", 0, "#2CB4FF"));
        right.add(createEChartsInfoVO("未完成", 0, "#ff9c39"));
    }

    // 创建ECharts信息对象
    private EChartsInfoVO createEChartsInfoVO(String name, int value, String color) {
        Map<String, String> itemStyle = new HashMap<>();
        itemStyle.put("color", color);
        return new EChartsInfoVO(name, value, itemStyle);
    }

    // 处理左侧数据（课时数和学习时间）
    private void processLeftData(Map<String, String> left, Integer leftCourseId, Set<Integer> courseIds, Long userId) {
        int section = 0;

        if (leftCourseId == null) {
            // 如果没有指定课程ID，则计算所有课程的学习记录
            for (Integer courseId : courseIds) {
                Map<Long, Set<String>> courseLearningRecords = UniversalUtil.getCourseLearningRecords(Long.valueOf(courseId), redisCache);
                if(courseLearningRecords != null && !courseLearningRecords.isEmpty()) {
                    section += courseLearningRecords.size();
                }
            }
        } else {
            // 如果指定了课程ID，则只计算该课程的学习记录
            Map<Long, Set<String>> courseLearningRecords = UniversalUtil.getCourseLearningRecords(Long.valueOf(leftCourseId), redisCache);
            if(courseLearningRecords != null && !courseLearningRecords.isEmpty()) {
                section = courseLearningRecords.size();
            }
        }

        // 设置左侧数据（课时数）
        left.put("section", String.valueOf(section));

        // 获取学习时间
        QueryWrapper<PlatformCCourseLearnTime> courseLearnTimeQueryWrapper = new QueryWrapper<>();
        courseLearnTimeQueryWrapper.eq("user_id", userId);
        if (leftCourseId == null) {
            courseLearnTimeQueryWrapper.in("course_id", courseIds);
        } else {
            courseLearnTimeQueryWrapper.eq("course_id", leftCourseId);
        }

        List<PlatformCCourseLearnTime> courseLearnTimes = courseLearnTimeMapper.selectList(courseLearnTimeQueryWrapper);
        BigDecimal totalTime = calculateTotalLearnTimeC(courseLearnTimes, "h");

        // 设置左侧数据（学习时间）
        left.put("studyTime", String.valueOf(totalTime));
    }

    // 处理中间数据（优秀率、合格率、不合格率）
    private void processMiddleData(List<EChartsInfoVO> middle, Integer middleCourseId, Set<Integer> courseIds, Long userId) {
        QueryWrapper<PlatformEExam> examQueryWrapper = new QueryWrapper<>();
        if (middleCourseId == null) {
            examQueryWrapper.in("exam_course", courseIds);
        } else {
            examQueryWrapper.eq("exam_course", middleCourseId);
        }

        List<PlatformEExam> exams = examMapper.selectList(examQueryWrapper);
        if (CollectionUtils.isEmpty(exams)) {
            // 如果没有考试记录，则添加默认数据
            addDefaultMiddleData(middle);
        } else {
            HashSet<Integer> examIds = new HashSet<>();
            exams.forEach(e -> examIds.add(e.getId()));
            QueryWrapper<PlatformEScore> scoreQueryWrapper = new QueryWrapper<>();
            scoreQueryWrapper.eq("student_id", userId);
            scoreQueryWrapper.eq("vetting_status", 1);
            scoreQueryWrapper.in("exam_id", examIds);
            List<PlatformEScore> scores = eScoreMapper.selectList(scoreQueryWrapper);

            if (CollectionUtils.isEmpty(scores)) {
                addDefaultMiddleData(middle);
            } else {
                // 统计优秀、合格、不合格的人数
                int youXiuNum = 0, heGeNum = 0, buJiGeNum = 0;
                for (PlatformEScore score : scores) {
                    Integer scoreTotalValue = score.getScoreTotalValue();
                    if (scoreTotalValue >= 85) {
                        youXiuNum++;
                    } else if (scoreTotalValue >= 60) {
                        heGeNum++;
                    } else {
                        buJiGeNum++;
                    }
                }
                middle.add(createEChartsInfoVO("优秀率", youXiuNum, "#2CB4FF"));
                middle.add(createEChartsInfoVO("合格率", heGeNum, "#51CE92"));
                middle.add(createEChartsInfoVO("不合格率", buJiGeNum, "#ff9c39"));
            }
        }
    }

    // 处理右侧数据（任务完成情况）
    private void processRightData(List<EChartsInfoVO> right, Integer rightCourseId, Set<Integer> courseIds, Long userId) {
        QueryWrapper<PlatformTTask> taskQueryWrapper = new QueryWrapper<>();
        if (rightCourseId == null) {
            taskQueryWrapper.in("task_course", courseIds);
        } else {
            taskQueryWrapper.eq("task_course", rightCourseId);
        }

        List<PlatformTTask> tasks = taskMapper.selectList(taskQueryWrapper);
        if (CollectionUtils.isEmpty(tasks)) {
            // 如果没有任务记录，则添加默认数据
            addDefaultTaskData(right);
        } else {
            HashSet<Integer> taskIds = new HashSet<>();
            tasks.forEach(t -> taskIds.add(t.getId()));
            QueryWrapper<PlatformTScore> tScoreQueryWrapper = new QueryWrapper<>();
            tScoreQueryWrapper.in("task_id", taskIds);
            tScoreQueryWrapper.eq("student_id", userId);
            List<PlatformTScore> tScores = tScoreMapper.selectList(tScoreQueryWrapper);

            if (CollectionUtils.isEmpty(tScores)) {
                addDefaultTaskData(right);
            } else {
                int wanChengNum = 0, weiWanChengNum = 0;
                for (PlatformTScore tScore : tScores) {
                    Integer score = tScore.getTaskStatus();
                    if (score == 1) {
                        wanChengNum++;
                    } else {
                        weiWanChengNum++;
                    }
                }
                right.add(createEChartsInfoVO("完成", wanChengNum, "#2CB4FF"));
                right.add(createEChartsInfoVO("未完成", weiWanChengNum, "#ff9c39"));
            }
        }
    }


    /**
     * 添加默认的右侧数据：优秀率、合格率、不及格率
     */
    private void addDefaultRightData(List<EChartsInfoVO> right) {
        String[] names = {"优秀率", "合格率", "不及格"};
        String[] colors = {"#2CB4FF", "#51CE92", "#ff9c39"};

        for (int i = 0; i < names.length; i++) {
            EChartsInfoVO eChartsInfoVO = new EChartsInfoVO();
            eChartsInfoVO.setName(names[i]);
            eChartsInfoVO.setValue(0);
            Map<String, String> itemStyle = new HashMap<>();
            itemStyle.put("color", colors[i]);
            eChartsInfoVO.setItemStyle(itemStyle);
            right.add(eChartsInfoVO);
        }
    }

    /**
     * 根据虚拟仿真ID查询左侧数据
     */
    private void addLeftData(Integer leftVirtualId, HashSet<Long> virtualIds, List<EChartsHistogramVO> left) {
        // 查找学习记录
        QueryWrapper<PlatformLLearn> learnQueryWrapper = new QueryWrapper<>();
        learnQueryWrapper.eq("learn_type", 0);  // 学习类型：0
        if (leftVirtualId != null) {
            learnQueryWrapper.eq("project_id", leftVirtualId);
        } else {
            learnQueryWrapper.in("project_id", virtualIds);
        }
        List<PlatformLLearn> learnList = learnMapper.selectList(learnQueryWrapper);
        Set<Long> learnPersonIds = new HashSet<>();
        learnList.forEach(l -> learnPersonIds.add(l.getLearnPersonId()));

        // 收集左侧数据
        List<String> name = new ArrayList<>();
        List<String> value = new ArrayList<>();
        name.add("实训人数（人）");
        value.add(String.valueOf(learnPersonIds.size()));
        name.add("实训人次（次）");
        value.add(String.valueOf(learnList.size()));

        // 计算平均运行时长
        QueryWrapper<PlatformUVirtualLearnTime> virtualLearnTimeQueryWrapper = new QueryWrapper<>();
        if (leftVirtualId != null) {
            virtualLearnTimeQueryWrapper.eq("pid", leftVirtualId);
        } else {
            virtualLearnTimeQueryWrapper.in("pid", virtualIds);
        }
        List<PlatformUVirtualLearnTime> virtualLearnTimeList = virtualLearnTimeMapper.selectList(virtualLearnTimeQueryWrapper);
        BigDecimal totalLearnTimeInMinutes = calculateTotalLearnTime(virtualLearnTimeList, "m");
        name.add("平均运行时长（min）");
        if(CollectionUtils.isEmpty(virtualLearnTimeList)){
            value.add("0");
        }else {
            value.add(String.valueOf(totalLearnTimeInMinutes.divide(BigDecimal.valueOf(virtualLearnTimeList.size()), 1, RoundingMode.HALF_UP)));
        }

        // 查询最大浏览量
        int allViewCount = getMaxViewCount(leftVirtualId, virtualIds);
        name.add("最大浏览量");
        value.add(String.valueOf(allViewCount));

        // 设置图表数据
        EChartsHistogramVO eChartsHistogramVO = new EChartsHistogramVO();
        eChartsHistogramVO.setName(name);
        eChartsHistogramVO.setValue(value);
        left.add(eChartsHistogramVO);
    }

    /**
     * 获取最大浏览量（根据虚拟仿真ID）
     */
    private int getMaxViewCount(Integer leftVirtualId, HashSet<Long> virtualIds) {
        int allViewCount = 0;
        if (leftVirtualId != null) {
            String viewKey = VIRTUAL_VIEWS_KEY_PREFIX + leftVirtualId;
            Object views = redisCache.getCacheMapValue(viewKey, "views");
            if (views != null) {
                allViewCount = Integer.parseInt(views.toString());
            }
        } else {
            for (Long virtualId : virtualIds) {
                String viewKey = VIRTUAL_VIEWS_KEY_PREFIX + virtualId;
                Object views = redisCache.getCacheMapValue(viewKey, "views");
                if (views != null) {
                    allViewCount += Integer.parseInt(views.toString());
                }
            }
        }
        return allViewCount;
    }

    /**
     * 根据虚拟仿真ID查询右侧数据
     */
    private void addRightData(Integer leftVirtualId, HashSet<Long> virtualIds, List<EChartsInfoVO> right) {
        // 查找学习成绩
        QueryWrapper<PlatformUVirtualStudy> virtualStudyQueryWrapper = new QueryWrapper<>();
        if (leftVirtualId != null) {
            virtualStudyQueryWrapper.eq("virtual_id", leftVirtualId);
        } else {
            virtualStudyQueryWrapper.in("virtual_id", virtualIds);
        }
        List<PlatformUVirtualStudy> virtualStudyList = virtualStudyMapper.selectList(virtualStudyQueryWrapper);

        if (CollectionUtils.isEmpty(virtualStudyList)) {
            // 如果没有成绩数据，添加默认数据
            addDefaultRightData(right);
        } else {
            // 统计优秀、合格、不及格人数
            int excellent = 0;
            int qualified = 0;
            int disqualification = 0;
            for (PlatformUVirtualStudy platformUVirtualStudy : virtualStudyList) {
                Integer value1 = platformUVirtualStudy.getValue();
                if (value1 != null) {
                    if (value1 >= 85) {
                        excellent++;
                    } else if (value1 >= 60) {
                        qualified++;
                    } else {
                        disqualification++;
                    }
                }
            }
            // 添加成绩数据到右侧
            addRightStudyData(excellent, qualified, disqualification, right);
        }
    }

    /**
     * 添加右侧学习成绩数据
     */
    private void addRightStudyData(int excellent, int qualified, int disqualification, List<EChartsInfoVO> right) {
        String[] names = {"优秀率", "合格率", "不及格"};
        int[] values = {excellent, qualified, disqualification};
        String[] colors = {"#2CB4FF", "#51CE92", "#ff9c39"};

        for (int i = 0; i < names.length; i++) {
            EChartsInfoVO eChartsInfoVO = new EChartsInfoVO();
            eChartsInfoVO.setName(names[i]);
            eChartsInfoVO.setValue(values[i]);
            Map<String, String> itemStyle = new HashMap<>();
            itemStyle.put("color", colors[i]);
            eChartsInfoVO.setItemStyle(itemStyle);
            right.add(eChartsInfoVO);
        }
    }


    // 计算所有虚拟学习时长总和的方法
    private BigDecimal calculateTotalLearnTime(List<PlatformUVirtualLearnTime> virtualLearnTimeList, String unit) {
        BigDecimal totalTime = BigDecimal.ZERO;  // 初始化总时间为0
        List<TimePeriod> timePeriods = new ArrayList<>();

        for (PlatformUVirtualLearnTime learnTime : virtualLearnTimeList) {
            // 获取每条记录的开始和结束时间
            Date startTime = learnTime.getStartTime();
            Date endTime = learnTime.getEndTime();

            if (startTime != null && endTime != null) {
                // 格式化时间为yyyy-MM-dd HH:mm:ss字符串
                String startStr = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime);
                String endStr = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime);

                TimePeriod timePeriod = new TimePeriod();
                timePeriod.setStartTime(startStr);
                timePeriod.setEndTime(endStr);
                timePeriods.add(timePeriod);
            }
        }
        totalTime = UniversalUtil.calculateTotalTimeDifference(timePeriods, unit);

        // 返回总时长
        return totalTime;
    }

    // 计算所有课程学习时长总和的方法
    private BigDecimal calculateTotalLearnTimeC(List<PlatformCCourseLearnTime> virtualLearnTimeList, String unit) {
        BigDecimal totalTime = BigDecimal.ZERO;  // 初始化总时间为0

        List<TimePeriod> timePeriods = new ArrayList<>();
        for (PlatformCCourseLearnTime learnTime : virtualLearnTimeList) {
            // 获取每条记录的开始和结束时间
            Date startTime = learnTime.getStartTime();
            Date endTime = learnTime.getEndTime();

            if (startTime != null && endTime != null) {
                // 格式化时间为yyyy-MM-dd HH:mm:ss字符串
                String startStr = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime);
                String endStr = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime);

                TimePeriod timePeriod = new TimePeriod();
                timePeriod.setStartTime(startStr);
                timePeriod.setEndTime(endStr);
                timePeriods.add(timePeriod);
            }
        }
        totalTime = UniversalUtil.calculateTotalTimeDifference(timePeriods, unit);

        // 返回总时长
        return totalTime;
    }

    // 获取默认的成绩分布（分数段均为0）
    private List<EChartsInfoVO> getDefaultScoreInfo() {
        List<EChartsInfoVO> StudentScore = new ArrayList<>();
        String[] scoreRanges = {"91-100", "81-90", "71-80", "61-70", "<60"};
        String[] itemStyleAll = {"#ff9c39", "#ff8a57", "#2cb4ff", "#51ce92", "#ff6550"};
        List<String> list = Arrays.asList(itemStyleAll);
        int i = 0;
        for (String range : scoreRanges) {
            EChartsInfoVO eChartsInfoVO = new EChartsInfoVO();
            eChartsInfoVO.setName(range);
            eChartsInfoVO.setValue(0);
            Map<String, String> itemStyle = new HashMap<>();
            itemStyle.put("color", list.get(i));
            eChartsInfoVO.setItemStyle(itemStyle);
            StudentScore.add(eChartsInfoVO);
            i++;
        }
        return StudentScore;
    }

    // 获取默认的作业完成情况（未完成和完成均为0）
    private List<EChartsInfoVO> getDefaultWorkInfo() {
        List<EChartsInfoVO> workFinish = new ArrayList<>();
        Map<String, String> itemStyle = new HashMap<>();
        EChartsInfoVO eChartsInfoVO6 = new EChartsInfoVO();
        eChartsInfoVO6.setName("未完成");
        eChartsInfoVO6.setValue(0);
        itemStyle.put("color", "#ff9c39");
        eChartsInfoVO6.setItemStyle(itemStyle);
        workFinish.add(eChartsInfoVO6);

        EChartsInfoVO eChartsInfoVO7 = new EChartsInfoVO();
        eChartsInfoVO7.setName("完成");
        eChartsInfoVO7.setValue(0);
        Map<String, String> itemStyle1 = new HashMap<>();
        itemStyle1.put("color", "#2cb4ff");
        eChartsInfoVO7.setItemStyle(itemStyle1);
        workFinish.add(eChartsInfoVO7);

        return workFinish;
    }

    // 处理课程未学习人数的逻辑
    private void handleNoStudyInfo(Integer studyNumCourseId, Set<Integer> peopleIds, List<EChartsInfoVO> courseNum) {
        // 查找这门课程的所有班级ID
        Integer[] deptIds = platformCCourseDeptMapper.selectByCourseId(studyNumCourseId);

        // 查找每个班级的所有用户
        ArrayList<WorkDeptUserVO> workDeptUserAllVOS = new ArrayList<>();
        for (Integer deptId : deptIds) {
            List<WorkDeptUserVO> workDeptUserVOS = userMapper.selectDeptUsers(Long.valueOf(deptId));
            workDeptUserAllVOS.addAll(workDeptUserVOS);
        }

        // 计算未学习人数
        int size = workDeptUserAllVOS.size();
        int noStudy = size - peopleIds.size();

        // 添加未学习人数
        EChartsInfoVO eChartsInfoVO1 = new EChartsInfoVO();
        eChartsInfoVO1.setName("未学习");
        eChartsInfoVO1.setValue(noStudy);
        courseNum.add(eChartsInfoVO1);
    }

    // 获取成绩分布信息
    private List<EChartsInfoVO> getScoreDistribution(Integer StudentScoreCourseId, Long userId) {
        // 构建查询条件，查询考试信息
        QueryWrapper<PlatformEExam> platformEExamQueryWrapper = new QueryWrapper<>();
        platformEExamQueryWrapper.eq("create_id", userId); // 查询当前用户创建的考试
        if (StudentScoreCourseId != null) {
            platformEExamQueryWrapper.eq("exam_course", StudentScoreCourseId); // 查询指定课程的考试
        }
        List<PlatformEExam> platformEExams = examMapper.selectList(platformEExamQueryWrapper);

        // 获取所有考试ID
        ArrayList<Integer> examIds = new ArrayList<>();
        for (PlatformEExam platformEExam : platformEExams) {
            examIds.add(platformEExam.getId());
        }

        List<EChartsInfoVO> StudentScore = new ArrayList<>();
        if (!examIds.isEmpty()) {
            // 查询成绩信息
            QueryWrapper<PlatformEScore> platformEScoreQueryWrapper = new QueryWrapper<>();
            platformEScoreQueryWrapper.in("exam_id", examIds);
            platformEScoreQueryWrapper.eq("vetting_status", 1); // 只查询审核通过的成绩
            List<PlatformEScore> platformEScores = eScoreMapper.selectList(platformEScoreQueryWrapper);

            // 按分数段统计学生数量
            StudentScore = calculateScoreDistribution(platformEScores);
        } else {
            // 如果没有成绩数据，设置所有分数段为0
            StudentScore = getDefaultScoreInfo();
        }
        return StudentScore;
    }

    // 根据成绩列表计算分数段分布
    private List<EChartsInfoVO> calculateScoreDistribution(List<PlatformEScore> platformEScores) {
        List<EChartsInfoVO> StudentScore = new ArrayList<>();

        // 按照分数段过滤成绩
        List<PlatformEScore> score100 = platformEScores.stream()
                .filter(item -> item.getExamTotalValue() >= 91 && item.getExamTotalValue() <= 100)
                .collect(Collectors.toList());
        List<PlatformEScore> score90 = platformEScores.stream()
                .filter(item -> item.getExamTotalValue() >= 81 && item.getExamTotalValue() <= 90)
                .collect(Collectors.toList());
        List<PlatformEScore> score80 = platformEScores.stream()
                .filter(item -> item.getExamTotalValue() >= 71 && item.getExamTotalValue() <= 80)
                .collect(Collectors.toList());
        List<PlatformEScore> score70 = platformEScores.stream()
                .filter(item -> item.getExamTotalValue() >= 61 && item.getExamTotalValue() <= 70)
                .collect(Collectors.toList());
        List<PlatformEScore> score60 = platformEScores.stream()
                .filter(item -> item.getExamTotalValue() <= 60)
                .collect(Collectors.toList());

        // 填充分数段数据
        // 为每个 EChartsInfoVO 创建新的 itemStyle
        Map<String, String> itemStyle1 = new HashMap<>();
        itemStyle1.put("color", "#ff9c39");
        StudentScore.add(new EChartsInfoVO("91-100", score100.size(), itemStyle1));

        Map<String, String> itemStyle2 = new HashMap<>();
        itemStyle2.put("color", "#ff8a57");
        StudentScore.add(new EChartsInfoVO("81-90", score90.size(), itemStyle2));

        Map<String, String> itemStyle3 = new HashMap<>();
        itemStyle3.put("color", "#2cb4ff");
        StudentScore.add(new EChartsInfoVO("71-80", score80.size(), itemStyle3));

        Map<String, String> itemStyle4 = new HashMap<>();
        itemStyle4.put("color", "#51ce92");
        StudentScore.add(new EChartsInfoVO("61-70", score70.size(), itemStyle4));

        Map<String, String> itemStyle5 = new HashMap<>();
        itemStyle5.put("color", "#ff6550");
        StudentScore.add(new EChartsInfoVO("<60", score60.size(), itemStyle5));


        return StudentScore;
    }

    // 获取作业完成情况
    private List<EChartsInfoVO> getWorkFinishInfo(Integer workFinishCourseId, Long userId) {
        // 查询作业信息
        QueryWrapper<PlatformTTask> taskQueryWrapper = new QueryWrapper<>();
        taskQueryWrapper.eq("create_id", userId); // 查询当前用户创建的作业
        if (workFinishCourseId != null) {
            taskQueryWrapper.eq("task_course", workFinishCourseId); // 查询指定课程的作业
        }
        List<PlatformTTask> platformTTasks = taskMapper.selectList(taskQueryWrapper);

        List<EChartsInfoVO> workFinish = new ArrayList<>();
        if (!platformTTasks.isEmpty()) {
            // 获取作业完成情况
            workFinish = calculateWorkFinish(platformTTasks);
        } else {
            // 如果没有作业，设置完成和未完成都为0
            workFinish = getDefaultWorkInfo();
        }
        return workFinish;
    }

    // 计算作业完成情况
    private List<EChartsInfoVO> calculateWorkFinish(List<PlatformTTask> platformTTasks) {
        // 获取所有作业ID
        List<Integer> taskIds = platformTTasks.stream()
                .map(PlatformTTask::getId)
                .collect(Collectors.toList());

        // 查询作业成绩
        QueryWrapper<PlatformTScore> platformTScoreQueryWrapper = new QueryWrapper<>();
        platformTScoreQueryWrapper.in("task_id", taskIds);
        List<PlatformTScore> platformTScores = tScoreMapper.selectList(platformTScoreQueryWrapper);

        // 根据作业状态分类
        List<PlatformTScore> finish = new ArrayList<>();
        List<PlatformTScore> noFinish = new ArrayList<>();
        for (PlatformTScore platformTScore : platformTScores) {
            if (platformTScore.getTaskStatus() == 0) {
                noFinish.add(platformTScore);
            } else {
                finish.add(platformTScore);
            }
        }

        // 返回作业完成情况数据
        List<EChartsInfoVO> workFinish = new ArrayList<>();
        Map<String, String> itemStyle = new HashMap<>();
        itemStyle.put("color", "#ff9c39");
        workFinish.add(new EChartsInfoVO("未完成", noFinish.size(), itemStyle));
        Map<String, String> itemStyle1 = new HashMap<>();
        itemStyle1.put("color", "#2cb4ff");
        workFinish.add(new EChartsInfoVO("完成", finish.size(), itemStyle1));

        return workFinish;
    }


    @Override
    public AjaxResult combinedSearching(Integer pageNum, Integer pageSize, String projectName) {
        if (null == pageNum) {
            pageNum = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }
        CombinedSearchingVO combinedSearchingVO = new CombinedSearchingVO();
        Page<PlatformCCourseVO> platformCCourseVOList = getPlatformCCourseVOS(pageNum, pageSize, projectName);
        Page<PlatformUVirtualVO> platformUVirtualVOList = getPlatformUVirtualVOS(pageNum, pageSize, projectName);
        Page<PlatformUResource> platformUResourceList = getPlatformUResources(pageNum, pageSize, projectName);
        combinedSearchingVO.setPlatformCCourseVOS(platformCCourseVOList);
        combinedSearchingVO.setPlatformUVirtualVOS(platformUVirtualVOList);
        combinedSearchingVO.setPlatformUResources(platformUResourceList);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", combinedSearchingVO);
    }

    private Page<PlatformUResource> getPlatformUResources(Integer pageNum, Integer pageSize, String projectName) {
        QueryWrapper<PlatformUResource> wrapper = new QueryWrapper<>();

        // 按资源名称过滤
        if (projectName != null && !projectName.isEmpty()) {
            wrapper.like("resource_name", projectName);
        }

        // 只查询已审核通过的资源
        wrapper.eq("vetting_status", 1);

        // 执行查询
        List<PlatformUResource> resourceList = resourceMapper.selectList(wrapper);

        // 获取Redis中的下载量并排序
        Map<Long, Integer> downloadCountMap = new HashMap<>();
        for (PlatformUResource resource : resourceList) {
            Integer downloadCount = redisCache.getCacheMapValue(DOWNLOAD_COUNT_KEY, resource.getId().toString());
            resource.setDownloadCount(downloadCount);
            downloadCountMap.put(resource.getId(), downloadCount != null ? downloadCount : 0);
        }

        // 根据下载量排序
        resourceList.sort((r1, r2) -> {
            // 从下载量映射表中获取两个资源的下载量
            int count1 = downloadCountMap.getOrDefault(r1.getId(), 0);
            int count2 = downloadCountMap.getOrDefault(r2.getId(), 0);

            // 根据下载量排序
            return Integer.compare(count2, count1);
        });


        // 分页处理
        int start = (pageNum - 1) * pageSize;
        int end = Math.min(start + pageSize, resourceList.size());
        List<PlatformUResource> paginatedList = resourceList.subList(start, end);

        // 将分页结果转换为 Page 对象
        Page<PlatformUResource> page = new Page<>(pageNum, pageSize);
        page.setRecords(paginatedList);
        page.setTotal(resourceList.size());
        return page;
    }

    private Page<PlatformUVirtualVO> getPlatformUVirtualVOS(Integer pageNum, Integer pageSize, String projectName) {
        Page<PlatformUVirtual> platformUVirtualPage = new Page<>(pageNum, pageSize);
        QueryWrapper<PlatformUVirtual> wrapper = new QueryWrapper<>();
        wrapper.eq("vetting_status", 1);
        if (null != projectName && !projectName.equals("")) {
            wrapper.like("virtual_name", projectName);
        }
        // 默认排序，先按评分再按上传时间排序
        wrapper.orderByDesc("grade", "create_time");
        platformUVirtualPage = virtualMapper.selectPage(platformUVirtualPage, wrapper);

        // 转换查询结果
        List<PlatformUVirtualVO> platformUVirtualVOS = new ArrayList<>();
        for (PlatformUVirtual record : platformUVirtualPage.getRecords()) {
            PlatformUVirtualVO platformUVirtualVO = convertToVO(record);
            platformUVirtualVOS.add(platformUVirtualVO);
        }

        // 设置分页结果
        Page<PlatformUVirtualVO> platformUVirtualVOPage = new Page<>(pageNum, pageSize);
        BeanUtils.copyProperties(platformUVirtualPage, platformUVirtualVOPage);
        platformUVirtualVOPage.setRecords(platformUVirtualVOS);

        return platformUVirtualVOPage;
    }

    private Page<PlatformCCourseVO> getPlatformCCourseVOS(Integer pageNum, Integer pageSize, String projectName) {
        QueryWrapper<PlatformCCourse> platformCCourseQueryWrapper = new QueryWrapper<>();
        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
            // 未登录用户，按普通用户处理
        } catch (ServiceException e) {

        }
        int roleId = 0;
        if (userId != null) {
            roleId = Math.toIntExact(sysUserRoleMapper.selectRoleIdbyUserId(userId)[0]);
        }
        boolean roleUser = (roleId == 5 || roleId == 0 || roleId == 7);// 普通用户和企业用户
        boolean roleTeacher = (roleId == 3);// 教师
        boolean roleStudent = (roleId == 4);// 学生
        boolean roleSystemAdmin = (roleId == 1 || roleId == 6);// 超级管理员
        boolean roleSchoolAdmin = (roleId == 2);// 学校管理员
        platformCCourseQueryWrapper.eq("course_visible", 0);    // 查询云课堂
        List<PlatformCCourse> platformCCourses = courseMapper.selectList(platformCCourseQueryWrapper);
        if (roleUser) {
            if (StringUtils.isNotEmpty(projectName)) {
                platformCCourses.removeIf(platformCCourse ->
                        !(platformCCourse.getCourseName().contains(projectName) || platformCCourse.getCreateBy().contains(projectName))
                );
            }
        }
        if (roleTeacher) {
            int teacherId = SecurityUtils.getUserId().intValue();
            QueryWrapper<PlatformCCourse> wrapper = new QueryWrapper<>();
            wrapper.eq("create_id", teacherId);
            wrapper.ne("course_visible", 0);     // 除去云课堂
            List<PlatformCCourse> teacherOwn = courseMapper.selectList(wrapper);
            if (!CollectionUtils.isEmpty(teacherOwn)) {
                platformCCourses.addAll(teacherOwn);
            }
            filterCourse(projectName, platformCCourses);
        }
        if (roleStudent) {
            int deptId = 0;
            try {
                deptId = Integer.parseInt(userMapper.selectUserById(userId).getClassId());
            } catch (ServiceException e) {

            }
            List<PlatformCCourse> studentCourse = new ArrayList<>();
            if (deptId != 0) {
                Integer[] courseId = platformCCourseDeptMapper.selectByDeptId(deptId);
                if (!CollectionUtils.isEmpty(Arrays.asList(courseId))) {
                    QueryWrapper<PlatformCCourse> wrapper = new QueryWrapper<>();
                    wrapper.in("id", Arrays.asList(courseId));
                    wrapper.ne("course_visible", 0);     // 除去云课堂
                    studentCourse = courseMapper.selectList(wrapper);
                }
                if (!CollectionUtils.isEmpty(studentCourse)) {
                    platformCCourses.addAll(studentCourse);
                }
            }
            if (StringUtils.isNotEmpty(projectName)) {
                platformCCourses.removeIf(platformCCourse ->
                        !(platformCCourse.getCourseName().contains(projectName) || platformCCourse.getCreateBy().contains(projectName))
                );
            }
        }
        if (roleSystemAdmin) {
            QueryWrapper<PlatformCCourse> systemAdminQW = new QueryWrapper<>();
            systemAdminQW.eq("vetting_status", 1);
            systemAdminQW.ne("course_visible", 2);
            List<PlatformCCourse> systemAdminCourses = courseMapper.selectList(systemAdminQW);
            filterCourse(projectName, systemAdminCourses);
            Page<PlatformCCourseVO> page = toPage(systemAdminCourses, pageNum, pageSize);
            return page;
        }
        if (roleSchoolAdmin) {
            Long schoolAdminDeptId = Long.parseLong(userMapper.selectUserById(userId).getClassId());
            List<SysDept> collegeDepts = deptMapper.selectChildrenDeptById(schoolAdminDeptId);
            List<Long> specialtyDeptIds = new ArrayList<>();
            List<Long> teacherIds = new ArrayList<>();
            if (!CollectionUtils.isEmpty(collegeDepts)) {
                for (SysDept collegeDept : collegeDepts) {
                    List<SysDept> collegeDeptInfo = deptMapper.selectChildrenDeptById(collegeDept.getDeptId());
                    if (CollectionUtils.isEmpty(collegeDeptInfo)) {
                        continue;
                    }
                    for (SysDept specialtyDept : collegeDeptInfo) {
                        specialtyDeptIds.add(specialtyDept.getDeptId());
                    }
                }
                if (!CollectionUtils.isEmpty(specialtyDeptIds)) {
                    for (Long specialtyDeptId : specialtyDeptIds) {
                        List<WorkDeptUserVO> workDeptUserVOS = userMapper.selectDeptUsers(specialtyDeptId);
                        for (WorkDeptUserVO workDeptUserVO : workDeptUserVOS) {
                            teacherIds.add(workDeptUserVO.getId());
                        }
                    }
                }
            }
            QueryWrapper<PlatformCCourse> wrapper = new QueryWrapper<>();
            List<PlatformCCourse> schoolAdminCourses = new ArrayList<>();
            if (!CollectionUtils.isEmpty(teacherIds)) {
                wrapper.in("create_id", teacherIds);
                wrapper.ne("course_visible", 2);
                schoolAdminCourses = courseMapper.selectList(wrapper);
                schoolAdminCourses.removeIf(platformCCourse -> platformCCourse.getCourseVisible() == 0);// 删除云课堂
            }
            if (!CollectionUtils.isEmpty(schoolAdminCourses)) {
                platformCCourses.removeAll(schoolAdminCourses);
            }
            filterCourse(projectName, platformCCourses);
        }
        Page<PlatformCCourseVO> page = toPage(platformCCourses, pageNum, pageSize);
        return page;
    }

    private void filterCourse(String courseName, List<PlatformCCourse> platformCCourses) {
        if (StringUtils.isNotEmpty(courseName)) {
            if (StringUtils.isNotEmpty(courseName)) {
                platformCCourses.removeIf(platformCCourse ->
                        !(platformCCourse.getCourseName().contains(courseName) || platformCCourse.getCreateBy().contains(courseName))
                );
            }
        }
    }

    private Page<PlatformCCourseVO> toPage(List<PlatformCCourse> courses, Integer pageNum, Integer pageSize) {
        // 过滤未审核通过的课程
        courses.removeIf(course -> course.getVettingStatus() != 1);

        // 默认按评分排序，再按上传时间排序
        courses.sort(Comparator.comparing(PlatformCCourse::getGrade).reversed()
                .thenComparing(Comparator.comparing(PlatformCCourse::getCreateTime).reversed()));

        // 确定分页参数
        int total = courses.size();
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        int start = Math.min((pageNum - 1) * pageSize, total);
        int end = Math.min(start + pageSize, total);

        // 获取当前页的数据
        List<PlatformCCourse> paginatedList = courses.subList(start, end);

        // 创建存储结果的列表
        ArrayList<PlatformCCourseVO> platformCCourseVOS = new ArrayList<>();

        // 获取用户ID，如果无法获取则捕获异常
        Integer userId = null;
        try {
            userId = SecurityUtils.getUserId().intValue();
        } catch (ServiceException e) {
            // 无法获取用户ID时，设置用户ID为null
        }

        for (PlatformCCourse platformCCourse : paginatedList) {
            PlatformCCourseVO platformCCourseVO = new PlatformCCourseVO();
            BeanUtils.copyProperties(platformCCourse, platformCCourseVO);

            if (userId == null) {
                // 如果无法获取用户ID，直接添加学习人数
                QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
                platformLLearnQueryWrapper.eq("project_id", platformCCourse.getId()).eq("learn_type", 1);
                List<PlatformLLearn> newList = new ArrayList<>();
                List<PlatformLLearn> platformLLearns = learnMapper.selectList(platformLLearnQueryWrapper);
                platformLLearns.stream().filter(UniversalUtil.distinctByKey(PlatformLLearn::getLearnPersonId)) // filter保留true的值
                        .forEach(newList::add);
                platformCCourseVO.setLearnNumber(newList.size());
                platformCCourseVOS.add(platformCCourseVO);
            } else {
                // 获取该课程是否被收藏
                QueryWrapper<PlatformSCollect> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("person_id", userId).eq("collect_type", 1).eq("project_id", platformCCourse.getId());
                int collectCount = Math.toIntExact(collectMapper.selectCount(queryWrapper));
                platformCCourseVO.setCollect(collectCount > 0 ? 1 : 0);

                // 添加学习人数
                QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
                platformLLearnQueryWrapper.eq("project_id", platformCCourse.getId()).eq("learn_type", 1);
                List<PlatformLLearn> platformLLearns = learnMapper.selectList(platformLLearnQueryWrapper);
                List<PlatformLLearn> newList = new ArrayList<>();
                platformLLearns.stream().filter(UniversalUtil.distinctByKey(PlatformLLearn::getLearnPersonId)) // filter保留true的值
                        .forEach(newList::add);
                platformCCourseVO.setLearnNumber(newList.size());

                platformCCourseVOS.add(platformCCourseVO);
            }
        }

        // 设置分页信息
        Page<PlatformCCourseVO> page = new Page<>(pageNum, pageSize);
        page.setRecords(platformCCourseVOS);
        page.setTotal(total);

        return page;
    }

    private LocalDate getStartDate(Integer time) {
        if (null == time || time == 0) {
            return LocalDate.now().minusDays(30); // 近30天
        } else if (time == 1) {
            return LocalDate.now().minusMonths(6); // 近半年
        } else if (time == 2) {
            return LocalDate.now().minusYears(1); // 近一年
        }
        return LocalDate.now();
    }

    /**
     * 将 PlatformUVirtual 实体转换为 PlatformUVirtualVO
     */
    private PlatformUVirtualVO convertToVO(PlatformUVirtual record) {
        PlatformUVirtualVO platformUVirtualVO = new PlatformUVirtualVO();
        BeanUtils.copyProperties(record, platformUVirtualVO);

        // 转换虚拟类型
        String virtualType = record.getVirtualType();
        Integer[] virtualTypeArray = UniversalUtil.stringToArray(virtualType, Integer::valueOf, Integer.class);
        platformUVirtualVO.setVirtualType(virtualTypeArray);

        // 转换专业ID
        String professionalId = record.getProfessionalId();
        Integer[] professionalIdArray = UniversalUtil.stringToArray(professionalId, Integer::valueOf, Integer.class);
        platformUVirtualVO.setProfessionalId(professionalIdArray);

        // 转换标签ID
        String softwareTag = record.getSoftwareTag();
        Long[] softwareTagIds = UniversalUtil.stringToArray(softwareTag, Long::valueOf, Long.class);
        platformUVirtualVO.setSoftwareTag(softwareTagIds);


        // 添加学习人数
        QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
        platformLLearnQueryWrapper.eq("project_id", platformUVirtualVO.getId()).eq("learn_type", 0);
        List<PlatformLLearn> newList = new ArrayList<>();
        List<PlatformLLearn> platformLLearns = learnMapper.selectList(platformLLearnQueryWrapper);
        platformLLearns.stream().filter(UniversalUtil.distinctByKey(PlatformLLearn::getLearnPersonId)) // filter保留true的值
                .forEach(newList::add);
        platformUVirtualVO.setLearnNumber(newList.size());

        // 如果有题库的话将题目由字符串转成对象
        if (StringUtils.isNotEmpty(record.getQuestionUrl())) {
            String questionInfo = record.getQuestionInfo();
            List<PlatformQQuestionVO> platformQQuestionVOS = JSON.parseArray(questionInfo, PlatformQQuestionVO.class);
            platformUVirtualVO.setPlatformQQuestionDTOs(platformQQuestionVOS);
        }

        // 判断该虚拟仿真是否被收藏
        // 获取用户ID，如果无法获取则捕获异常
        Integer userId = null;
        try {
            userId = SecurityUtils.getUserId().intValue();
        } catch (ServiceException e) {
            platformUVirtualVO.setCollect(0);
            return platformUVirtualVO;
        }
        QueryWrapper<PlatformSCollect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("person_id", userId).eq("collect_type", 0).eq("project_id", platformUVirtualVO.getId());
        int collectCount = Math.toIntExact(collectMapper.selectCount(queryWrapper));
        platformUVirtualVO.setCollect(collectCount > 0 ? 1 : 0);

        return platformUVirtualVO;
    }

    public int getOnlineLearningCount(int learnType) {
        String redisKey = learnType == 0 ? VIRTUAL_SIMULATION_KEY : COURSE_KEY;
        return redisCache.getCacheSetSize(redisKey);
    }

    /**
     * 每天午夜执行一次，清理指定的Redis键
     */
    @Scheduled(cron = "0 0 0 * * ?")
    // @Scheduled(initialDelay = 5000, fixedRate = Long.MAX_VALUE)  //项目启动后五秒执行
    public void cleanUpRedisData() {
        // 清除指定的Redis键
        redisCache.deleteObject(VIRTUAL_SIMULATION_KEY);
        redisCache.deleteObject(COURSE_KEY);
        redisCache.deleteObject(lOOK_NUM);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        String beijingTime = sdf.format(new Date());

        System.out.println("Cleared specified Redis keys at: " + beijingTime);

    }
}
